package com.wsy.wsyojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.wsy.wsyojcodesandbox.model.ExecuteCodeRequest;
import com.wsy.wsyojcodesandbox.model.ExecuteCodeResponse;
import com.wsy.wsyojcodesandbox.model.ExecuteMessage;
import com.wsy.wsyojcodesandbox.model.JudgeInfo;
import com.wsy.wsyojcodesandbox.utils.ProcessUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class JavaDockerCodeSandboxUsingTemplate extends JavaCodeSandboxTemplate {
    //最大运行时间
    private static final long TIME_OUT = 5000L;
    //开关
    private static Boolean FIRST_INIT = true;

    private static final Object lock;

    //静态代码块初始化
    static {
//        TRIE = new Trie(blackList);
        lock = new Object();
    }

    /**
     * Docker 自定义运行代码方法
     * @param userCodeFile
     * @param inputList
     * @return
     */
    @Override
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        StopWatch stopWatch = new StopWatch();
        //3. 创建容器，上传编译代码到容器内
        //默认DockerClient, 创建Docker交互进程
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String image = "openjdk:8-alpine";

//        异步拉取镜像
        synchronized (lock) {
            if (FIRST_INIT) {
                PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
                PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                    @Override
                    public void onNext(PullResponseItem item) {
                        System.out.println("下载镜像..." + item.getStatus());
                        super.onNext(item);
                    }
                };
                try {
                    pullImageCmd
                            .exec(pullImageResultCallback)
                            .awaitCompletion();
                } catch (InterruptedException e) {
                    System.out.println("拉取镜像异常！");
                    throw new RuntimeException(e);
                }
                System.out.println("下载完成");
                FIRST_INIT = false;
            }
        }

        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        //创建时就指定本地文件同步(映射、挂载)到容器中的某个位置
        HostConfig hostConfig = new HostConfig();
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        hostConfig.withMemory(100 * 1000 * 1000L); //给容器设置100M内存，实现内存控制
        hostConfig.withCpuCount(1L);

        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withTty(true)
                .withCmd("echo", "Hello Docker")
                .exec();
        System.out.println(createContainerResponse);
        //获取创建的容器id
        String containerId = createContainerResponse.getId();

        //启动刚刚创建的容器
        dockerClient.startContainerCmd(containerId).exec();
        //先保证让容器启动完毕后再去加载日志，不然因为异步的原因，可能日志先执行了
//        Thread.sleep(5000L);

        // docker exec {container name}(容器名) java -cp /app(刚刚挂载的目录下) Main 1 3
        //准备List接收每一个输入对应的返回信息
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String[] arg = inputArgs.split(" ");
            String[] cmdArr = ArrayUtil.append(new String[] {"java", "-cp", "/app", "Main"}, arg);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArr)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("执行命令为：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errMessage = {null};
            //判断是否超时
            final boolean[] timeout = {true};
            //为异步执行代码定义一个回调函数，执行完后启动该类
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    //执行完程序后，执行最后这个方法
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if(StreamType.STDERR.equals(streamType)) {
                        errMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errMessage[0]);
                    }else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };

            final long[] maxMemory = {0L};
            //获取占用的内存(周期，因为内存占用时时刻刻是不同的)
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用: " + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(maxMemory[0], statistics.getMemoryStats().getUsage());
                }
                @Override
                public void onStart(Closeable closeable) {

                }
                @Override
                public void onError(Throwable throwable) {

                }
                @Override
                public void onComplete() {

                }
                @Override
                public void close() throws IOException {

                }
            });

            try {
                //开始计时
                stopWatch.start();

                //docker中执行代码, 因异步执行,必须加上awaitCompletion
                //等待执行完毕，去调用上面定义的回调函数
                dockerClient.execStartCmd(execCreateCmdResponse.getId())
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);

                //结束计时
                stopWatch.stop();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errMessage[0]);
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        return executeMessageList;
    }
}
